﻿using org.se.fs.model;
using org.se.fs.presenter.IView;
using org.se.fs.presenter.Library;

namespace org.se.fs.presenter.View
{
    public class Splash
    {
        private readonly ISplash _view;
        private readonly ITask.ISplash _task;
        public event FormEvent.FormEventHandler OnManualConfig;
        public event FormEvent.FormEventHandler OnNotify;

        public Splash(ISplash view) : this(view, new Task.Splash()) { }

        public Splash(ISplash view, ITask.ISplash task)
        {
            _view = view;
            _task = task;
            _task.OnLoadConfig += TaskOnLoadConfig;
            _task.OnCheckConnection += TaskOnCheckConnection;
        }

        public void Initialize()
        {
            _view.ProgressBar = 0;
            _view.Status = "Loading Configuration";
            _task.LoadConfig();
        }

        void TaskOnLoadConfig(object source, FormEvent e)
        {
            if (e.IsSuccess)
            {
                SetStatus("Loading Setting Configuration", 45);
                System.Threading.Thread.Sleep(500);
                _task.CheckConnection();
            }
            else
            {
                DataContext.ProviderType = ProviderType.Mysql;
                OnManualConfig(this, new FormEvent(true));
            }
        }

        void TaskOnCheckConnection(object source, FormEvent e)
        {
            if (e.IsSuccess)
            {
                SetStatus("Done", 100);
                System.Threading.Thread.Sleep(500);
                OnNotify(this, new FormEvent(e.IsSuccess));
            }
            else
                OnManualConfig(this, new FormEvent(true));
        }

        void SetStatus(string message, int percent)
        {
            _view.Status = message + " . . .";
            _view.ProgressBar = percent;
        }
    }
}